package com.ja10.books;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Calendar;

import com.example.books.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ReserveDetailActivity extends Activity{
	
	SimpleDatabaseHelper helper = null;
	SQLiteDatabase db = null;
	private ReserveList reserve = null;
	
	SharedPreferences settings = null;
	String loginId = null;
	
	ReserveDay reserve_day = new ReserveDay();
	
	String table 		= null;
	int stock_books 	= 0;
	int rental_books 	= 0;
	int reserve_members = 0;
	String reserve_plan_day = null;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_reserve_detail);
		
		// 各ウィジェットの取得
		ImageView img 				= (ImageView)findViewById(R.id.img);
		TextView title 				= (TextView)findViewById(R.id.txt_title);
		TextView writer 			= (TextView)findViewById(R.id.txt_writer);
		TextView publisher 			= (TextView)findViewById(R.id.txt_publisher);
		TextView isbn 				= (TextView)findViewById(R.id.txt_isbn);
		TextView publicationDate 	= (TextView)findViewById(R.id.txt_publicationDate);
		TextView content 			= (TextView)findViewById(R.id.txt_content);
		TextView reserve_plan_date 	= (TextView)findViewById(R.id.txt_reserve_plan_date);
		TextView reserve_date 		= (TextView)findViewById(R.id.txt_reserve_date);
		
		// ネットワーク接続を取得
		ConnectivityManager cm = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
		boolean net = new NetworkGet(cm).net;
		
		// インテントを取得
		Intent i = this.getIntent();
		String getIsbn = i.getStringExtra("isbn");
		
		// ヘルパーを準備
		helper = new SimpleDatabaseHelper(this);
					
		// 端末データベースの取得
		db = helper.getReadableDatabase();
		String[] params = { getIsbn };
		Cursor cs = db.query("reserves", null, "isbn = ?", params, null, null, null);
		if(cs.moveToFirst()) {
			reserve = new ReserveList();
			reserve.setId(cs.getInt(0));
			reserve.setGenreName(cs.getString(1));
			reserve.setPublisherName(cs.getString(2));
			reserve.setTitle(cs.getString(3));
			reserve.setWriter(cs.getString(4));
			reserve.setContent(cs.getString(5));
			reserve.setPublicationDate(cs.getString(6));
			reserve.setPictureBmp(cs.getBlob(7));
			reserve.setIsbn(cs.getString(8));
			reserve.setReserveDate_str(cs.getString(9));
			reserve.setReserveDate(cs.getString(9));
			reserve.setReservePlanDate(cs.getString(10));
		}
		cs.close();
		db.close();
		
		// ボタン操作の不可設定
		if(!net) {
			((Button)findViewById(R.id.btnReserveDelete)).setEnabled(false);
		}
		
		//貸出可能予定日の更新
		try {
			stock_books 	= reserve_day.Numbers("books",reserve.getIsbn());
			rental_books	= reserve_day.RentalNumbers(reserve.getIsbn());
			reserve_members = reserve_day.ReserveMembers(reserve.getReserveDate(), reserve.getIsbn());
			
			reserve_plan_day= reserve_day.ReturnPlanDate(reserve.getReserveDate(), reserve.getIsbn(), reserve_members, stock_books,true); 
		
			Log.d("reserve_plan_day", reserve_plan_day);
			
		} catch (SQLException e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		}
		
		if(reserve != null) {
			// 各ウィジェットにデータをセット
			title.setText(reserve.getTitle());
			writer.setText(reserve.getWriter());
			publisher.setText(reserve.getPublisherName());
			isbn.setText(reserve.getIsbn());
			if(reserve.getPublicationDate() != null) {
				publicationDate.setText(reserve.getPublicationDate().replaceAll("-", "/"));
			}
			if(reserve.getContent() != null || reserve.getContent().length() > 0) {
				content.setText(reserve.getContent());
			} else {
				content.setVisibility(View.GONE);
			}
			
			
			
			img.setImageBitmap(reserve.getPictureBmp());
//			reserve_plan_date.setText(reserve.getReservePlanDate());
			reserve_plan_date.setText(reserve_plan_day);
			reserve_date.setText(reserve.getReserveDate_str());
		}
		
	}
//----------------　[ログイン]ボタンクリック時に呼び出されるメソッド
		public void btnLogin_onClick(View view){
				
		// LoginActivityへのインテントを作成
			Intent i = new Intent(this, LoginActivity.class);
		// アクティビティを起動
			startActivity(i);
		}
		
//----------------　[メインメニュー]ボタンクリック時に呼び出されるメソッド
		public void btnMenu_onClick(View view){
				
			Intent i = new Intent(this, MainActivity.class);
			startActivity(i);
			finish();
		}
		
//----------------　[予約取り消し]ボタンクリック時に呼び出されるメソッド
		public void btnReserveDelete_onClick(View view){
			
			settings = getSharedPreferences(LoginActivity.PREFERENCES_FILE_NAME, Activity.MODE_PRIVATE);
			loginId = settings.getString("id", "");
			
			// ログイン時
			if(!"".equals(loginId)) {
				
				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
				
		        // アラートダイアログのメッセージを設定します
		        alertDialogBuilder.setMessage("選択された予約を取消してよろしいでしょうか？");
		        
		        alertDialogBuilder.setPositiveButton("キャンセル",
		                new DialogInterface.OnClickListener() {
		                    @Override
		                    public void onClick(DialogInterface dialog, int which) {
		                    }
		                });
		        alertDialogBuilder.setNegativeButton("予約取消",
		                new DialogInterface.OnClickListener() {
		                    @Override
		                    public void onClick(DialogInterface dialog, int which) {
		                    	// 取り消しの実行
		                    	reserveDelete();
		                    }
		                });
		        alertDialogBuilder.setCancelable(true);
		        AlertDialog alertDialog = alertDialogBuilder.create();
		        alertDialog.show();
			}
			// 未ログイン時
			else {
				Intent i = new Intent(this, LoginActivity.class);
				i.putExtra("move", 2);
				startActivity(i);
			}
		}
		
		// 予約取り消し
		public void reserveDelete() {
			
			db = helper.getReadableDatabase();
			
			// トランザクションの開始
			db.beginTransaction();
			
			// 端末内DBより削除する予約IDを取得
			String[] delId = { Integer.toString(reserve.getId()) };
			
			// 端末内DBより削除の実行
			int sqliteResult = db.delete("reserves", "id = ?", delId);
			
			// 予約取消書籍のISBNを取得
			String bookIsbn = reserve.getIsbn();
			
			// 予約情報を取得するSQL文の用意
			String sql = "select r.id, user_id, book_isbn from members as m, reserves as r " +
							"where m.id = r.member_id and user_id = '" + loginId + "' and book_isbn = '" + bookIsbn + "'";
			
			Connection con = null;
			Statement smt = null;
			
			int mysqlResult = 0;
			
			try {
				con = DBManager.getConnection();
				smt = con.createStatement();
				ResultSet rs = smt.executeQuery(sql);
				
				if(rs.first() && sqliteResult > 0) {
					// 外部DBより削除する予約IDの取得
					int id = rs.getInt(1);
					// 予約削除するSQL文の用意
					sql = "delete from reserves where id = " + id;
					// 予約削除の実行
					mysqlResult = smt.executeUpdate(sql);
				}
				// 削除された場合
				if(mysqlResult > 0) {
					// 端末内DB削除の確定
					db.setTransactionSuccessful();
					Toast.makeText(this, "予約を1件取消しました", Toast.LENGTH_SHORT).show();
				}
				// 削除できなかった場合
				else {
					Toast.makeText(this, "エラー", Toast.LENGTH_SHORT).show();
				}
			} catch(SQLException e) {
				e.printStackTrace();
			} finally {
				if(smt != null) {
					try {
						smt.close();
					} catch(SQLException ignore) {
						// none
					}
				}
				if(con != null) {
					try {
						con.close();
					} catch(SQLException ignore) {
						// none
					}
				}
				// トランザクションの終了
				db.endTransaction();
				db.close();
				finish();
			}
		}
		
		@Override
		public boolean onCreateOptionsMenu(Menu menu) {
			// Inflate the menu; this adds items to the action bar if it is present.
			getMenuInflater().inflate(R.menu.main, menu);
			return true;
		}
		

}
